const querystring = require("querystring");
const reader = require('./util/staticReader');
const db = require('../db/sqlite');
const PageConfig = require('./util/page-config');
const util = require('./util/util');

const showList = (res, req) =>{
	db.all(function (logArr) {
		res.end(JSON.stringify(logArr));
	});
};

const saveData = (dataObj) => {
	db.insert(dataObj);
};

const viewRealtimeLog = (resp)=>{
	reader.readFile( PageConfig.INDEX ).then(({
		content,
		contentType,
	})=>{
		resp.writeHead(200, {
			"Content-Type": contentType,
			"Content-Length": content.length
		});
		resp.end(content);
	}).catch(err=>{
		resp.writeHead(500, {
			"Content-Type": "text/html"
		});
		resp.end();
	});
};

let timer = null;
const timeout = 800; // delay for collection
let list = [];

const broadcast = ( socket, data)=>{
	clearTimeout( timer );
	list = list.concat( data );
	timer = setTimeout(() => {
		socket.broadcast('new', list);
		list = [];
	}, timeout);
};

function report(res, req, socket) {
	if (req.method === 'GET') {
		// usage :
		// new Image().src = `/report?data=${JSON.stringify( {test: 1} )}`;
		const {
			data
		} = util.parseRequest(req.url);
		const ret = JSON.parse(data);
		console.log(ret);
		broadcast(socket, ret);
		// saveData(ret);
		res.end('success');
	}
	else {
		var body = '';

		req.on('data', function (data) {
			body += data;
			// Too much POST data, kill the connection!
			// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
			if (body.length > 1e6)
				req.connection.destroy();
		});

		req.on('end', function () {
			var post = querystring.parse(body);
			console.log('post: ', post);

			try {
				var data = JSON.parse(post);
				broadcast(socket, data);
			} catch (e) {
				broadcast(socket, post);
			}
			saveData(post);
			res.end('success');
		});
	}
}
// test
/*
var log = {
	para: {
		click: 'test',
		page: window.location.href
	}
};
new Image().src = '/report?log=' + JSON.stringify(log);
*/

exports.viewRealtimeLog = viewRealtimeLog;
exports.showList = showList;
exports.report = report;